import logging
import datetime
import sys
import queue
import requests
from .globals import g


# 获取logger实例，如果参数为空则返回root logger
logger = logging.getLogger("autotest")
g.logger = logger
# 指定logger输出格式
formatter = logging.Formatter('%(asctime)s %(filename)s %(funcName)s [%(levelname)s]: #  %(message)s')
# TDP日志
queue_autotest_log = queue.Queue()  # test_result / run_log


def tdp_headlers():
    return  {'token': g.tdp_token, 'sid': g.sid,}


def test_case_result_post(data: dict):
    requests.post(
        f'http://{g.tdp_server_addr}/tdp/slave?c=autotestLog&type=case_result&task_id={g.task_id}',
        json=data, headers=tdp_headlers(), verify=False
    )


# def test_step_result_post(data: dict):
#     requests.post(
#         f'http://{g.tdp_server_addr}/tdp/slave?c=autotestLog&type=step_result&task_id={g.task_id}',
#         json=data, headers=tdp_headlers())


def snapshot_post(file, file_name, file_name_post):
    data = {
        'type': 'snapshot',
        'data': file,
        'file_name': file_name,
        'file_name_post': file_name_post,
        'request_param': ''
    }
    try:
        data['request_param'] = f'result_case_id={g.result_case_id}'
    except:
        pass
    queue_autotest_log.put(data)

class TdpLogHandler(logging.Handler):
    def emit(self, record: logging.LogRecord):
        # data = record.getMessage()
        rec = self.format(record)
        data = {
            'type': 'text',
            'data': rec,
            'request_param': ''
        }
        try:
            data['request_param'] = f'result_case_id={g.result_case_id}'
        except:
            pass
        queue_autotest_log.put(data)


def today():
    now = datetime.datetime.now()
    return now.strftime('%Y%m%d')


# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.formatter = formatter  # 也可以直接给formatter赋值

# TDP日志
tdp_handler = TdpLogHandler()
tdp_handler.formatter = formatter

# 为logger添加的日志处理器
# logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.addHandler(tdp_handler)

# 指定日志的最低输出级别，默认为WARN级别
# DEBUG，INFO，WARNING，ERROR，CRITICAL
logger.setLevel(logging.INFO)



